﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using KWT.DRG_DIP.DB;
using KWT.DRG_DIP.PO.Basic;

namespace KWT.DRG_DIP.API.Infrastructure
{
    public class RoleFuncFilter : Attribute, IActionFilter
    {
        private readonly EFContext _efContext;
        public RoleFuncFilter(EFContext efContext)
        {

            _efContext = efContext;

        }

        public void OnActionExecuted(ActionExecutedContext context)
        {

        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            bool actionAnonymous = context.ActionDescriptor.EndpointMetadata.Any(x => x is AllowAnonymousAttribute);

            string path = context.ActionDescriptor.AttributeRouteInfo.Template;
            if (!actionAnonymous)
            {
                string role_id = context.HttpContext?.User.Claims.ElementAt(1).Value;
                var q1 = _efContext.Set<Sys_Func>().AsQueryable();
                var q2 = _efContext.Set<Role_Func>().AsQueryable();

                var q = from x in q1
                        join y in q2
                        on x.FuncID equals y.FuncID
                        select new { x.Url, y.RoleID };
                var flag = q.Any(x => x.RoleID == role_id && x.Url == path);
                if (!flag)
                {
                    context.Result = new ContentResult { StatusCode = 403, ContentType = "application/json;charset=utf-8", Content = path };
                }
            }
        }
    }
}
